Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:
We'll lead you through each part which you'll implement in Python.
When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.
# The new version of dataset is only available in the tfds-nightly package.
#%pip --no-cache-dir install tensorflow-datasets --user
# Had problems to load the dataset, so upgraded tensorflow und used the newest version of the dataset
%pip --no-cache-dir install tfds-nightly --user
!pip install tensorflow --upgrade --user
# DON'T MISS TO RESTART THE KERNEL
Collecting tfds-nightly
Downloading https://files.pythonhosted.org/packages/a7/4f/2cab08f674d316af507b7c7e009ce325bb86425411b276852bf76599a55c/tfds_nightly-4.4.0.dev202110180107-py3-none-any.whl (4.0MB)
|████████████████████████████████| 4.0MB 4.6MB/s eta 0:00:01 |█████████▌ | 1.2MB 4.6MB/s eta 0:00:01 |████████████████████████████▍ | 3.6MB 4.6MB/s eta 0:00:01
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.3.1.1)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.12.0)
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.14.0)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.22.0)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.2.1)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (4.36.1)
Collecting typing-extensions; python_version < "3.8"
Downloading https://files.pythonhosted.org/packages/74/60/18783336cc7fcdd95dae91d73477830aa53f5d3181ae4fe20491d7fc3199/typing_extensions-3.10.0.2-py3-none-any.whl
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.17.4)
Collecting protobuf>=3.12.2
Downloading https://files.pythonhosted.org/packages/6e/62/eeec5be0b69442d2ffc7acdf54469fb4c76aa42288fe38decc537973a90a/protobuf-3.18.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.1MB)
|████████████████████████████████| 1.1MB 23.6MB/s eta 0:00:01
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.1.0)
Collecting importlib-resources; python_version < "3.9"
Downloading https://files.pythonhosted.org/packages/11/8e/84a6a778a1160cefcef1192a7bd26e4e6689981553aff13c2b2b6f1c352f/importlib_resources-5.2.3-py3-none-any.whl
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.8.1)
Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.18.2)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tfds-nightly) (1.6.0)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (1.24.2)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2.8)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2019.11.28)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
Collecting zipp>=3.1.0; python_version < "3.10"
Downloading https://files.pythonhosted.org/packages/bd/df/d4a4974a3e3957fd1c1fa3082366d7fff6e428ddb55f074bf64876f8e8ad/zipp-3.6.0-py3-none-any.whl
Installing collected packages: typing-extensions, protobuf, zipp, importlib-resources, tfds-nightly
WARNING: The script tfds is installed in '/root/.local/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed importlib-resources-5.2.3 protobuf-3.18.1 tfds-nightly-4.4.0.dev202110180107 typing-extensions-3.10.0.2 zipp-3.6.0
Note: you may need to restart the kernel to use updated packages.
Collecting tensorflow
Downloading https://files.pythonhosted.org/packages/8f/11/97aa4f0cbc771d07faf6a413559f05565af7891dbb5cedaa066be743ea61/tensorflow-2.6.0-cp37-cp37m-manylinux2010_x86_64.whl (458.3MB)
|████████████▌ | 178.7MB 21.9MB/s eta 0:00:13 | | 112kB 4.6MB/s eta 0:01:41 | | 1.1MB 4.6MB/s eta 0:01:41 |▍ | 5.0MB 4.6MB/s eta 0:01:40 |▌ | 7.3MB 4.6MB/s eta 0:01:40 |▋ | 8.6MB 4.6MB/s eta 0:01:39 |▊ | 10.8MB 4.6MB/s eta 0:01:39 |█ | 14.5MB 4.6MB/s eta 0:01:38 |█▏ | 17.0MB 4.6MB/s eta 0:01:37 |█▍ | 19.4MB 4.6MB/s eta 0:01:37 |█▌ | 20.9MB 4.6MB/s eta 0:01:37 |█▌ | 22.0MB 4.6MB/s eta 0:01:36 |█▋ | 22.9MB 17.4MB/s eta 0:00:26 |██▍ | 33.7MB 17.4MB/s eta 0:00:25 |██▍ | 34.9MB 17.4MB/s eta 0:00:25 |██▋ | 37.7MB 17.4MB/s eta 0:00:25 |███▍ | 47.7MB 26.7MB/s eta 0:00:16 |███▍ | 48.8MB 26.7MB/s eta 0:00:16 |███▌ | 50.0MB 26.7MB/s eta 0:00:16 |███▋ | 51.1MB 26.7MB/s eta 0:00:16 |███▊ | 53.3MB 26.7MB/s eta 0:00:16 |███▉ | 54.3MB 26.7MB/s eta 0:00:16 |████ | 56.6MB 26.7MB/s eta 0:00:16 |████ | 57.8MB 26.7MB/s eta 0:00:15 |████▌ | 64.3MB 26.7MB/s eta 0:00:15 |████▊ | 68.3MB 26.7MB/s eta 0:00:15 |████▉ | 69.6MB 31.8MB/s eta 0:00:13 |█████ | 72.4MB 31.8MB/s eta 0:00:13 |█████▎ | 76.0MB 31.8MB/s eta 0:00:13 |█████▍ | 77.2MB 31.8MB/s eta 0:00:13 |█████▊ | 82.1MB 31.8MB/s eta 0:00:12 |█████▉ | 83.3MB 31.8MB/s eta 0:00:12 |██████▍ | 91.4MB 31.8MB/s eta 0:00:12 |██████▌ | 93.7MB 10.0MB/s eta 0:00:37 |██████▊ | 96.0MB 10.0MB/s eta 0:00:37 |██████▉ | 98.5MB 10.0MB/s eta 0:00:36 |███████▏ | 102.3MB 10.0MB/s eta 0:00:36 |███████▉ | 112.3MB 10.0MB/s eta 0:00:35 |████████ | 114.5MB 34.3MB/s eta 0:00:11 |████████▎ | 118.0MB 34.3MB/s eta 0:00:10 |████████▌ | 121.5MB 34.3MB/s eta 0:00:10 |████████▌ | 122.3MB 34.3MB/s eta 0:00:10 |████████▋ | 122.8MB 34.3MB/s eta 0:00:10 |████████▊ | 124.7MB 34.3MB/s eta 0:00:10 |█████████ | 129.1MB 8.8MB/s eta 0:00:38 |█████████▎ | 132.6MB 8.8MB/s eta 0:00:38 |█████████▍ | 134.7MB 8.8MB/s eta 0:00:37 |█████████▌ | 136.6MB 8.8MB/s eta 0:00:37 |█████████▋ | 137.6MB 8.8MB/s eta 0:00:37 |█████████▊ | 138.7MB 8.8MB/s eta 0:00:37 |██████████ | 143.0MB 8.8MB/s eta 0:00:36 |██████████ | 144.2MB 8.8MB/s eta 0:00:36 |██████████▋ | 151.3MB 10.3MB/s eta 0:00:30 |██████████▋ | 152.3MB 10.3MB/s eta 0:00:30 |██████████▊ | 153.1MB 10.3MB/s eta 0:00:30 |██████████▊ | 153.9MB 10.3MB/s eta 0:00:30 |███████████ | 156.5MB 10.3MB/s eta 0:00:30 |███████████▏ | 160.4MB 10.3MB/s eta 0:00:30 |███████████▎ | 161.4MB 10.3MB/s eta 0:00:29 |███████████▍ | 162.5MB 10.3MB/s eta 0:00:29 |███████████▍ | 163.7MB 10.3MB/s eta 0:00:29 |███████████▌ | 164.9MB 10.3MB/s eta 0:00:29 |████████████▎ | 175.1MB 21.9MB/s eta 0:00:13 |████████████▎ | 176.2MB 21.9MB/s eta 0:00:13 |███████████████████████████████▋| 452.2MB 25.8MB/s eta 0:00:01 |████████████▋ | 180.9MB 21.9MB/s eta 0:00:13 |████████████▊ | 182.1MB 21.9MB/s eta 0:00:13 |████████████▉ | 183.1MB 21.9MB/s eta 0:00:13 |█████████████ | 186.3MB 21.9MB/s eta 0:00:13 |█████████████▏ | 188.5MB 22.9MB/s eta 0:00:12 |█████████████▎ | 189.6MB 22.9MB/s eta 0:00:12 |█████████████▎ | 190.6MB 22.9MB/s eta 0:00:12 |█████████████▌ | 193.5MB 22.9MB/s eta 0:00:12 |█████████████▉ | 197.7MB 22.9MB/s eta 0:00:12 |██████████████ | 201.6MB 22.9MB/s eta 0:00:12 |███████████████ | 213.3MB 26.8MB/s eta 0:00:10 |███████████████ | 214.7MB 26.8MB/s eta 0:00:10 |███████████████▋ | 223.7MB 26.8MB/s eta 0:00:09 |███████████████▉ | 227.5MB 26.8MB/s eta 0:00:09 |████████████████ | 228.5MB 31.3MB/s eta 0:00:08 |████████████████ | 229.4MB 31.3MB/s eta 0:00:08 |████████████████ | 230.5MB 31.3MB/s eta 0:00:08 |████████████████▏ | 231.5MB 31.3MB/s eta 0:00:08 |████████████████▎ | 232.4MB 31.3MB/s eta 0:00:08 |████████████████▍ | 234.1MB 31.3MB/s eta 0:00:08 |████████████████▋ | 237.9MB 31.3MB/s eta 0:00:08 |████████████████▊ | 240.1MB 31.3MB/s eta 0:00:07 |████████████████▉ | 241.0MB 31.3MB/s eta 0:00:07 |█████████████████ | 242.1MB 31.3MB/s eta 0:00:07 |█████████████████▏ | 246.4MB 17.6MB/s eta 0:00:13 |█████████████████▎ | 247.4MB 17.6MB/s eta 0:00:12 |█████████████████▌ | 251.3MB 17.6MB/s eta 0:00:12 |█████████████████▉ | 256.1MB 17.6MB/s eta 0:00:12 |██████████████████ | 258.2MB 17.6MB/s eta 0:00:12 |██████████████████▏ | 260.6MB 17.6MB/s eta 0:00:12 |██████████████████▎ | 261.6MB 17.6MB/s eta 0:00:12 |██████████████████▍ | 262.8MB 17.6MB/s eta 0:00:12 |██████████████████▋ | 267.2MB 23.7MB/s eta 0:00:09 |███████████████████ | 270.8MB 23.7MB/s eta 0:00:08 |███████████████████ | 273.1MB 23.7MB/s eta 0:00:08 |███████████████████▏ | 274.3MB 23.7MB/s eta 0:00:08 |███████████████████▎ | 275.5MB 23.7MB/s eta 0:00:08 |███████████████████▌ | 279.5MB 23.7MB/s eta 0:00:08 |███████████████████▋ | 281.6MB 23.7MB/s eta 0:00:08 |███████████████████▊ | 282.6MB 23.7MB/s eta 0:00:08 |████████████████████ | 287.5MB 27.2MB/s eta 0:00:07 |████████████████████▏ | 288.4MB 27.2MB/s eta 0:00:07 |████████████████████▋ | 294.7MB 27.2MB/s eta 0:00:07 |████████████████████▉ | 297.7MB 27.2MB/s eta 0:00:06 |████████████████████▉ | 298.8MB 27.2MB/s eta 0:00:06 |█████████████████████ | 299.8MB 27.2MB/s eta 0:00:06 |█████████████████████▍ | 306.1MB 7.2MB/s eta 0:00:22 |█████████████████████▌ | 308.2MB 7.2MB/s eta 0:00:21 |█████████████████████▊ | 311.1MB 7.2MB/s eta 0:00:21 |█████████████████████▉ | 312.2MB 7.2MB/s eta 0:00:21 |█████████████████████▉ | 313.2MB 7.2MB/s eta 0:00:21 |██████████████████████ | 315.5MB 7.2MB/s eta 0:00:20 |██████████████████████▏ | 316.7MB 7.2MB/s eta 0:00:20 |██████████████████████▍ | 320.2MB 7.2MB/s eta 0:00:20 |███████████████████████ | 330.9MB 19.1MB/s eta 0:00:07 |███████████████████████▍ | 335.2MB 19.1MB/s eta 0:00:07 |███████████████████████▉ | 341.1MB 19.1MB/s eta 0:00:07 |████████████████████████ | 342.9MB 19.1MB/s eta 0:00:07 |████████████████████████ | 343.8MB 19.1MB/s eta 0:00:07 |████████████████████████▍ | 349.0MB 21.8MB/s eta 0:00:06 |████████████████████████▍ | 349.9MB 21.8MB/s eta 0:00:05 |████████████████████████▋ | 352.4MB 21.8MB/s eta 0:00:05 |████████████████████████▊ | 353.3MB 21.8MB/s eta 0:00:05 |████████████████████████▊ | 354.3MB 21.8MB/s eta 0:00:05 |█████████████████████████ | 358.5MB 21.8MB/s eta 0:00:05 |█████████████████████████ | 359.2MB 21.8MB/s eta 0:00:05 |█████████████████████████▏ | 360.1MB 7.3MB/s eta 0:00:14 |█████████████████████████▎ | 362.6MB 7.3MB/s eta 0:00:14 |█████████████████████████▍ | 363.4MB 7.3MB/s eta 0:00:13 |█████████████████████████▌ | 365.0MB 7.3MB/s eta 0:00:13 |█████████████████████████▋ | 366.6MB 7.3MB/s eta 0:00:13 |█████████████████████████▊ | 368.3MB 7.3MB/s eta 0:00:13 |█████████████████████████▊ | 369.0MB 7.3MB/s eta 0:00:13 |█████████████████████████▉ | 369.9MB 7.3MB/s eta 0:00:13 |█████████████████████████▉ | 370.5MB 7.3MB/s eta 0:00:12 |██████████████████████████ | 371.4MB 7.3MB/s eta 0:00:12 |██████████████████████████ | 373.0MB 7.3MB/s eta 0:00:12 |██████████████████████████▎ | 376.7MB 23.9MB/s eta 0:00:04 |██████████████████████████▍ | 377.6MB 23.9MB/s eta 0:00:04 |██████████████████████████▍ | 378.5MB 23.9MB/s eta 0:00:04 |██████████████████████████▋ | 380.4MB 23.9MB/s eta 0:00:04 |██████████████████████████▋ | 381.5MB 23.9MB/s eta 0:00:04 |██████████████████████████▊ | 382.4MB 23.9MB/s eta 0:00:04 |██████████████████████████▊ | 383.3MB 23.9MB/s eta 0:00:04 |██████████████████████████▉ | 384.2MB 23.9MB/s eta 0:00:04 |███████████████████████████ | 386.2MB 23.9MB/s eta 0:00:04 |███████████████████████████ | 387.3MB 23.9MB/s eta 0:00:03 |███████████████████████████▌ | 393.5MB 7.6MB/s eta 0:00:09 |███████████████████████████▋ | 394.6MB 7.6MB/s eta 0:00:09 |███████████████████████████▋ | 395.7MB 7.6MB/s eta 0:00:09 |███████████████████████████▊ | 397.8MB 7.6MB/s eta 0:00:08 |███████████████████████████▉ | 398.7MB 7.6MB/s eta 0:00:08 |████████████████████████████ | 399.8MB 7.6MB/s eta 0:00:08 |████████████████████████████▏ | 404.0MB 7.6MB/s eta 0:00:08 |████████████████████████████▎ | 405.1MB 7.6MB/s eta 0:00:07 |████████████████████████████▌ | 408.1MB 7.6MB/s eta 0:00:07 |████████████████████████████▋ | 410.1MB 7.6MB/s eta 0:00:07 |████████████████████████████▊ | 410.9MB 7.6MB/s eta 0:00:07 |████████████████████████████▉ | 412.9MB 13.9MB/s eta 0:00:04 |█████████████████████████████ | 414.7MB 13.9MB/s eta 0:00:04 |█████████████████████████████ | 415.7MB 13.9MB/s eta 0:00:04 |█████████████████████████████ | 416.7MB 13.9MB/s eta 0:00:03 |█████████████████████████████▏ | 418.4MB 13.9MB/s eta 0:00:03 |█████████████████████████████▍ | 421.1MB 13.9MB/s eta 0:00:03 |█████████████████████████████▋ | 423.9MB 13.9MB/s eta 0:00:03 |█████████████████████████████▊ | 425.0MB 13.9MB/s eta 0:00:03 |█████████████████████████████▉ | 428.0MB 13.9MB/s eta 0:00:03 |██████████████████████████████ | 429.1MB 13.9MB/s eta 0:00:03 |██████████████████████████████ | 430.0MB 14.5MB/s eta 0:00:02 |██████████████████████████████ | 430.9MB 14.5MB/s eta 0:00:02 |██████████████████████████████▏ | 431.8MB 14.5MB/s eta 0:00:02 |██████████████████████████████▎ | 432.8MB 14.5MB/s eta 0:00:02 |██████████████████████████████▌ | 437.1MB 14.5MB/s eta 0:00:02 |██████████████████████████████▋ | 439.2MB 14.5MB/s eta 0:00:02 |██████████████████████████████▉ | 442.3MB 14.5MB/s eta 0:00:02 |███████████████████████████████ | 444.2MB 14.5MB/s eta 0:00:01 |███████████████████████████████ | 445.2MB 14.5MB/s eta 0:00:01 |███████████████████████████████▏| 447.1MB 14.5MB/s eta 0:00:01 |███████████████████████████████▍| 450.3MB 25.8MB/s eta 0:00:01 |███████████████████████████████▌| 451.3MB 25.8MB/s eta 0:00:01 |████████████████████████████████| 458.3MB 15kB/s s eta 0:00:01 |███████████████████████████████▉| 455.3MB 25.8MB/s eta 0:00:01 |███████████████████████████████▉| 456.3MB 25.8MB/s eta 0:00:01
Collecting flatbuffers~=1.12.0
Downloading https://files.pythonhosted.org/packages/eb/26/712e578c5f14e26ae3314c39a1bdc4eb2ec2f4ddc89b708cf8e0a0d20423/flatbuffers-1.12-py2.py3-none-any.whl
Collecting absl-py~=0.10
Downloading https://files.pythonhosted.org/packages/a0/b3/dba58c285e9720979b55574496c819322653f8e6d1d6cf9101c187c7d972/absl_py-0.14.1-py3-none-any.whl (131kB)
|████████████████████████████████| 133kB 23.6MB/s eta 0:00:01
Collecting tensorboard~=2.6
Downloading https://files.pythonhosted.org/packages/2d/eb/80f75ab480cfbd032442f06ec7c15ef88376c5ef7fd6f6bf2e0e03b47e31/tensorboard-2.7.0-py3-none-any.whl (5.8MB)
|████████████████████████████████| 5.8MB 69kB/s eta 0:00:01 |▍ | 61kB 6.1MB/s eta 0:00:01 |██████████▏ | 1.8MB 8.1MB/s eta 0:00:01 |████████████████████▌ | 3.7MB 8.1MB/s eta 0:00:01
Collecting clang~=5.0
Downloading https://files.pythonhosted.org/packages/32/12/e17c1220f8ca587add2e076ebb28b6c4551fcc730e3c69a5f49679ad28e9/clang-5.0.tar.gz
Collecting h5py~=3.1.0
Downloading https://files.pythonhosted.org/packages/9d/74/9eae2bedd8201ab464308f42c601a12d79727a1c87f0c867fdefb212c6cf/h5py-3.1.0-cp37-cp37m-manylinux1_x86_64.whl (4.0MB)
|████████████████████████████████| 4.0MB 16.1MB/s eta 0:00:01
Collecting wrapt~=1.12.1
Downloading https://files.pythonhosted.org/packages/82/f7/e43cefbe88c5fd371f4cf0cf5eb3feccd07515af9fd6cf7dbf1d1793a797/wrapt-1.12.1.tar.gz
Requirement already satisfied, skipping upgrade: termcolor~=1.1.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.1.0)
Collecting keras-preprocessing~=1.1.2
Downloading https://files.pythonhosted.org/packages/79/4c/7c3275a01e12ef9368a892926ab932b33bb13d55794881e3573482b378a7/Keras_Preprocessing-1.1.2-py2.py3-none-any.whl (42kB)
|████████████████████████████████| 51kB 5.9MB/s eta 0:00:01
Collecting grpcio<2.0,>=1.37.0
Downloading https://files.pythonhosted.org/packages/fe/58/aa3ef8bbf78679ab431aef8a8484c3da8290a6b470dbe170000759d845da/grpcio-1.41.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.9MB)
|████████████████████████████████| 3.9MB 34.6MB/s eta 0:00:01
Collecting astunparse~=1.6.3
Downloading https://files.pythonhosted.org/packages/2b/03/13dde6512ad7b4557eb792fbcf0c653af6076b81e5941d36ec61f7ce6028/astunparse-1.6.3-py2.py3-none-any.whl
Collecting keras~=2.6
Downloading https://files.pythonhosted.org/packages/5a/38/04d9b7fb53acdf861df2c4505fa96b06c779817a511e94b8882d284ba360/keras-2.6.0-py2.py3-none-any.whl (1.3MB)
|████████████████████████████████| 1.3MB 15.0MB/s eta 0:00:01 |█████████████▏ | 532kB 15.0MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: protobuf>=3.9.2 in /root/.local/lib/python3.7/site-packages (from tensorflow) (3.18.1)
Collecting typing-extensions~=3.7.4
Downloading https://files.pythonhosted.org/packages/60/7a/e881b5abb54db0e6e671ab088d079c57ce54e8a01a3ca443f561ccadb37e/typing_extensions-3.7.4.3-py3-none-any.whl
Collecting six~=1.15.0
Downloading https://files.pythonhosted.org/packages/ee/ff/48bde5c0f013094d729fe4b0316ba2a24774b3ff1c52d924a8a4cb04078a/six-1.15.0-py2.py3-none-any.whl
Collecting opt-einsum~=3.3.0
Downloading https://files.pythonhosted.org/packages/bc/19/404708a7e54ad2798907210462fd950c3442ea51acc8790f3da48d2bee8b/opt_einsum-3.3.0-py3-none-any.whl (65kB)
|████████████████████████████████| 71kB 5.6MB/s eta 0:00:01
Collecting numpy~=1.19.2
Downloading https://files.pythonhosted.org/packages/08/d6/a6aaa29fea945bc6c61d11f6e0697b325ff7446de5ffd62c2fa02f627048/numpy-1.19.5-cp37-cp37m-manylinux2010_x86_64.whl (14.8MB)
|████████████████████████████████| 14.8MB 7.9MB/s eta 0:00:01 |████████▋ | 4.0MB 7.9MB/s eta 0:00:02 |███████████ | 5.1MB 7.9MB/s eta 0:00:02 |█████████████▌ | 6.3MB 7.9MB/s eta 0:00:02 |███████████████▎ | 7.1MB 7.9MB/s eta 0:00:01 |██████████████████████▉ | 10.6MB 7.9MB/s eta 0:00:01 |█████████████████████████▌ | 11.8MB 7.9MB/s eta 0:00:01 |███████████████████████████████▏| 14.4MB 7.9MB/s eta 0:00:01
Collecting gast==0.4.0
Downloading https://files.pythonhosted.org/packages/b6/48/583c032b79ae5b3daa02225a675aeb673e58d2cb698e78510feceb11958c/gast-0.4.0-py3-none-any.whl
Collecting tensorflow-estimator~=2.6
Downloading https://files.pythonhosted.org/packages/c8/54/1b2f1e22a2670546cc02e4df1b80425edaee02133173bb91aa0f6d3d0293/tensorflow_estimator-2.6.0-py2.py3-none-any.whl (462kB)
|████████████████████████████████| 471kB 17.1MB/s eta 0:00:01
Collecting google-pasta~=0.2
Downloading https://files.pythonhosted.org/packages/a3/de/c648ef6835192e6e2cc03f40b19eeda4382c49b5bafb43d88b931c4c74ac/google_pasta-0.2.0-py3-none-any.whl (57kB)
|████████████████████████████████| 61kB 7.9MB/s eta 0:00:01
Collecting wheel~=0.35
Downloading https://files.pythonhosted.org/packages/04/80/cad93b40262f5d09f6de82adbee452fd43cdff60830b56a74c5930f7e277/wheel-0.37.0-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: werkzeug>=0.11.15 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.6->tensorflow) (0.16.0)
Collecting tensorboard-data-server<0.7.0,>=0.6.0
Downloading https://files.pythonhosted.org/packages/60/f9/802efd84988bffd9f644c03b6e66fde8e76c3aa33db4279ddd11c5d61f4b/tensorboard_data_server-0.6.1-py3-none-manylinux2010_x86_64.whl (4.9MB)
|████████████████████████████████| 4.9MB 27.8MB/s eta 0:00:01 |▎ | 40kB 33.9MB/s eta 0:00:01 |██████████████████ | 2.8MB 27.8MB/s eta 0:00:01 |████████████████████████████████| 4.9MB 27.8MB/s
Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.6->tensorflow) (3.1.1)
Collecting google-auth-oauthlib<0.5,>=0.4.1
Downloading https://files.pythonhosted.org/packages/b1/0e/0636cc1448a7abc444fb1b3a63655e294e0d2d49092dc3de05241be6d43c/google_auth_oauthlib-0.4.6-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: setuptools>=41.0.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.6->tensorflow) (41.4.0)
Collecting google-auth<3,>=1.6.3
Downloading https://files.pythonhosted.org/packages/83/13/9dc9121d7efca28ba3275e583262f8aff6798488fac50ae39c3099d0197d/google_auth-2.3.0-py2.py3-none-any.whl (154kB)
|████████████████████████████████| 163kB 15.1MB/s eta 0:00:01
Collecting tensorboard-plugin-wit>=1.6.0
Downloading https://files.pythonhosted.org/packages/1a/c1/499e600ba0c618b451cd9c425ae1c177249940a2086316552fee7d86c954/tensorboard_plugin_wit-1.8.0-py3-none-any.whl (781kB)
|████████████████████████████████| 788kB 8.0MB/s eta 0:00:01 |████████▉ | 215kB 8.0MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.6->tensorflow) (2.22.0)
Collecting cached-property; python_version < "3.8"
Downloading https://files.pythonhosted.org/packages/48/19/f2090f7dad41e225c7f2326e4cfe6fff49e57dedb5b53636c9551f86b069/cached_property-1.5.2-py2.py3-none-any.whl
Collecting requests-oauthlib>=0.7.0
Downloading https://files.pythonhosted.org/packages/a3/12/b92740d845ab62ea4edf04d2f4164d82532b5a0b03836d4d4e71c6f3d379/requests_oauthlib-1.3.0-py2.py3-none-any.whl
Collecting cachetools<5.0,>=2.0.0
Downloading https://files.pythonhosted.org/packages/ea/c1/4740af52db75e6dbdd57fc7e9478439815bbac549c1c05881be27d19a17d/cachetools-4.2.4-py3-none-any.whl
Collecting pyasn1-modules>=0.2.1
Downloading https://files.pythonhosted.org/packages/95/de/214830a981892a3e286c3794f41ae67a4495df1108c3da8a9f62159b9a9d/pyasn1_modules-0.2.8-py2.py3-none-any.whl (155kB)
|████████████████████████████████| 163kB 27.8MB/s eta 0:00:01
Collecting rsa<5,>=3.1.4
Downloading https://files.pythonhosted.org/packages/e9/93/0c0f002031f18b53af7a6166103c02b9c0667be528944137cc954ec921b3/rsa-4.7.2-py3-none-any.whl
Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (2.8)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (2019.11.28)
Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (3.0.4)
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (1.24.2)
Collecting oauthlib>=3.0.0
Downloading https://files.pythonhosted.org/packages/e8/5d/9dd1c29e5a786525f6342f6c1d812ed2e37edc653ad297048c1668988053/oauthlib-3.1.1-py2.py3-none-any.whl (146kB)
|████████████████████████████████| 153kB 31.5MB/s eta 0:00:01
Collecting pyasn1<0.5.0,>=0.4.6
Downloading https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl (77kB)
|████████████████████████████████| 81kB 5.3MB/s eta 0:00:01
Building wheels for collected packages: clang, wrapt
Building wheel for clang (setup.py) ... done
Created wheel for clang: filename=clang-5.0-cp37-none-any.whl size=30704 sha256=57ffd5af19a64254f503e989ff516a7dcc4d525d17ad2095e0e0ea215685ce65
Stored in directory: /root/.cache/pip/wheels/a1/d0/fb/f47e814ad88e0741b0ff6fc57bc4044f61c44cb707a68de6b3
Building wheel for wrapt (setup.py) ... done
Created wheel for wrapt: filename=wrapt-1.12.1-cp37-cp37m-linux_x86_64.whl size=70990 sha256=193af9ddb215cd3a3381e9e24170175cbcdb53ba1ece46d9f07005686370f4eb
Stored in directory: /root/.cache/pip/wheels/b1/c2/ed/d62208260edbd3fa7156545c00ef966f45f2063d0a84f8208a
Successfully built clang wrapt
Installing collected packages: flatbuffers, six, absl-py, tensorboard-data-server, oauthlib, requests-oauthlib, cachetools, pyasn1, pyasn1-modules, rsa, google-auth, google-auth-oauthlib, numpy, tensorboard-plugin-wit, grpcio, wheel, tensorboard, clang, cached-property, h5py, wrapt, keras-preprocessing, astunparse, keras, typing-extensions, opt-einsum, gast, tensorflow-estimator, google-pasta, tensorflow
WARNING: The scripts pyrsa-decrypt, pyrsa-encrypt, pyrsa-keygen, pyrsa-priv2pub, pyrsa-sign and pyrsa-verify are installed in '/root/.local/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
WARNING: The script google-oauthlib-tool is installed in '/root/.local/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
WARNING: The scripts f2py, f2py3 and f2py3.7 are installed in '/root/.local/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
WARNING: The script wheel is installed in '/root/.local/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
WARNING: The script tensorboard is installed in '/root/.local/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Found existing installation: typing-extensions 3.10.0.2
Uninstalling typing-extensions-3.10.0.2:
Successfully uninstalled typing-extensions-3.10.0.2
WARNING: The scripts estimator_ckpt_converter, import_pb_to_tensorboard, saved_model_cli, tensorboard, tf_upgrade_v2, tflite_convert, toco and toco_from_protos are installed in '/root/.local/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed absl-py-0.14.1 astunparse-1.6.3 cached-property-1.5.2 cachetools-4.2.4 clang-5.0 flatbuffers-1.12 gast-0.4.0 google-auth-2.3.0 google-auth-oauthlib-0.4.6 google-pasta-0.2.0 grpcio-1.41.0 h5py-3.1.0 keras-2.6.0 keras-preprocessing-1.1.2 numpy-1.19.5 oauthlib-3.1.1 opt-einsum-3.3.0 pyasn1-0.4.8 pyasn1-modules-0.2.8 requests-oauthlib-1.3.0 rsa-4.7.2 six-1.15.0 tensorboard-2.7.0 tensorboard-data-server-0.6.1 tensorboard-plugin-wit-1.8.0 tensorflow-2.6.0 tensorflow-estimator-2.6.0 typing-extensions-3.7.4.3 wheel-0.37.0 wrapt-1.12.1
# Import TensorFlow
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub
# TODO: Make all other necessary imports.
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import numpy as np
import matplotlib.pyplot as plt
import time
Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.
# Download data to default local directory "~/tensorflow_datasets"
!python -m tensorflow_datasets.scripts.download_and_prepare --register_checksums=True --datasets=oxford_flowers102
# TODO: Load the dataset with TensorFlow Datasets. Hint: use tfds.load()
dataset, dataset_info = tfds.load('oxford_flowers102', with_info=True, as_supervised=True)
# TODO: Create a training set, a validation set and a test set.
training_set, validation_set, test_set = dataset["train"], dataset["validation"], dataset["test"]
2021-10-18 15:10:19.464415: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2021-10-18 15:10:19.464469: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):
File "/opt/conda/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/opt/conda/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/root/.local/lib/python3.7/site-packages/tensorflow_datasets/scripts/download_and_prepare.py", line 25, in <module>
from tensorflow_datasets.scripts.cli import main as main_cli
File "/root/.local/lib/python3.7/site-packages/tensorflow_datasets/scripts/cli/main.py", line 40, in <module>
from tensorflow_datasets.scripts.utils import flag_utils
ModuleNotFoundError: No module named 'tensorflow_datasets.scripts.utils'
Downloading and preparing dataset 328.90 MiB (download: 328.90 MiB, generated: 331.34 MiB, total: 660.25 MiB) to /root/tensorflow_datasets/oxford_flowers102/2.1.1...
Dataset oxford_flowers102 downloaded and prepared to /root/tensorflow_datasets/oxford_flowers102/2.1.1. Subsequent calls will reuse this data.
# exploring the dataset info
dataset_info
tfds.core.DatasetInfo(
name='oxford_flowers102',
full_name='oxford_flowers102/2.1.1',
description="""
The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly occurring
in the United Kingdom. Each class consists of between 40 and 258 images. The images have
large scale, pose and light variations. In addition, there are categories that have large
variations within the category and several very similar categories.
The dataset is divided into a training set, a validation set and a test set.
The training set and validation set each consist of 10 images per class (totalling 1020 images each).
The test set consists of the remaining 6149 images (minimum 20 per class).
Note: The dataset by default comes with a test size larger than the train
size. For more info see this [issue](https://github.com/tensorflow/datasets/issues/3022).
""",
homepage='https://www.robots.ox.ac.uk/~vgg/data/flowers/102/',
data_path='/root/tensorflow_datasets/oxford_flowers102/2.1.1',
download_size=328.90 MiB,
dataset_size=331.34 MiB,
features=FeaturesDict({
'file_name': Text(shape=(), dtype=tf.string),
'image': Image(shape=(None, None, 3), dtype=tf.uint8),
'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=102),
}),
supervised_keys=('image', 'label'),
disable_shuffling=False,
splits={
'test': <SplitInfo num_examples=6149, num_shards=2>,
'train': <SplitInfo num_examples=1020, num_shards=1>,
'validation': <SplitInfo num_examples=1020, num_shards=1>,
},
citation="""@InProceedings{Nilsback08,
author = "Nilsback, M-E. and Zisserman, A.",
title = "Automated Flower Classification over a Large Number of Classes",
booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing",
year = "2008",
month = "Dec"
}""",
)
# TODO: Get the number of examples in each set from the dataset info.
num_train = dataset_info.splits["train"].num_examples
num_valid = dataset_info.splits["validation"].num_examples
num_test = dataset_info.splits["test"].num_examples
# TODO: Get the number of classes in the dataset from the dataset info.
num_labels = dataset_info.features["label"].num_classes
# TODO: Print the shape and corresponding label of 3 images in the training set.
i = 1
for image, label in training_set.take(3):
print("The shape of the {}. image is {}".format(i ,image.shape))
print(f"The corresponding label is {label}\n")
i += 1
The shape of the 1. image is (500, 667, 3) The corresponding label is 72 The shape of the 2. image is (500, 666, 3) The corresponding label is 84 The shape of the 3. image is (670, 500, 3) The corresponding label is 70
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding image label.
for image, label in training_set.take(1):
plt.imshow(image)
title = label
plt.title(f"The Label is {title}")
plt.show()
You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.
import json
with open('label_map.json', 'r') as f:
class_names = json.load(f)
# check out the names of the flowers in the class dict
class_names
{'21': 'fire lily',
'3': 'canterbury bells',
'45': 'bolero deep blue',
'1': 'pink primrose',
'34': 'mexican aster',
'27': 'prince of wales feathers',
'7': 'moon orchid',
'16': 'globe-flower',
'25': 'grape hyacinth',
'26': 'corn poppy',
'79': 'toad lily',
'39': 'siam tulip',
'24': 'red ginger',
'67': 'spring crocus',
'35': 'alpine sea holly',
'32': 'garden phlox',
'10': 'globe thistle',
'6': 'tiger lily',
'93': 'ball moss',
'33': 'love in the mist',
'9': 'monkshood',
'102': 'blackberry lily',
'14': 'spear thistle',
'19': 'balloon flower',
'100': 'blanket flower',
'13': 'king protea',
'49': 'oxeye daisy',
'15': 'yellow iris',
'61': 'cautleya spicata',
'31': 'carnation',
'64': 'silverbush',
'68': 'bearded iris',
'63': 'black-eyed susan',
'69': 'windflower',
'62': 'japanese anemone',
'20': 'giant white arum lily',
'38': 'great masterwort',
'4': 'sweet pea',
'86': 'tree mallow',
'101': 'trumpet creeper',
'42': 'daffodil',
'22': 'pincushion flower',
'2': 'hard-leaved pocket orchid',
'54': 'sunflower',
'66': 'osteospermum',
'70': 'tree poppy',
'85': 'desert-rose',
'99': 'bromelia',
'87': 'magnolia',
'5': 'english marigold',
'92': 'bee balm',
'28': 'stemless gentian',
'97': 'mallow',
'57': 'gaura',
'40': 'lenten rose',
'47': 'marigold',
'59': 'orange dahlia',
'48': 'buttercup',
'55': 'pelargonium',
'36': 'ruby-lipped cattleya',
'91': 'hippeastrum',
'29': 'artichoke',
'71': 'gazania',
'90': 'canna lily',
'18': 'peruvian lily',
'98': 'mexican petunia',
'8': 'bird of paradise',
'30': 'sweet william',
'17': 'purple coneflower',
'52': 'wild pansy',
'84': 'columbine',
'12': "colt's foot",
'11': 'snapdragon',
'96': 'camellia',
'23': 'fritillary',
'50': 'common dandelion',
'44': 'poinsettia',
'53': 'primula',
'72': 'azalea',
'65': 'californian poppy',
'80': 'anthurium',
'76': 'morning glory',
'37': 'cape flower',
'56': 'bishop of llandaff',
'60': 'pink-yellow dahlia',
'82': 'clematis',
'58': 'geranium',
'75': 'thorn apple',
'41': 'barbeton daisy',
'95': 'bougainvillea',
'43': 'sword lily',
'83': 'hibiscus',
'78': 'lotus lotus',
'88': 'cyclamen',
'94': 'foxglove',
'81': 'frangipani',
'74': 'rose',
'89': 'watercress',
'73': 'water lily',
'46': 'wallflower',
'77': 'passion flower',
'51': 'petunia'}
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding class name.
for image, label in training_set.take(1):
plt.imshow(image)
# needed to shift the label by 1. The class names dictionary starts at 1, not 0.
title = class_names[str(label.numpy()+1)].capitalize()
plt.title(f"The Label is {title}")
plt.show()
# check the dtype of the images
image.dtype
tf.uint8
# TODO: Create a pipeline for each set.
image_size = 224
batch_size = 64
def image_format(image, label):
"""first change the dtype of the images to float. In the next step resize the images to the given image_size
and normalize the data. Returns the image and label"""
image = tf.cast(image, tf.float32)
image = tf.image.resize(image, (image_size, image_size))
image /= 255
return image, label
training_batches = training_set.shuffle(num_train*2).map(image_format).batch(batch_size).prefetch(1)
validation_batches = validation_set.map(image_format).batch(batch_size).prefetch(1)
testing_batches = test_set.map(image_format).batch(batch_size).prefetch(1)
Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.
We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!
Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:
We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!
When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.
Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.
# Getting the MobileNet_V2 pretrained model
URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
feature_extractor = hub.KerasLayer(URL, input_shape=(image_size, image_size,3))
feature_extractor.trainable = False
# Some Randomness in flipping and rotating the images as a preprocessing step
data_augmentation = tf.keras.Sequential([
tf.keras.layers.experimental.preprocessing.RandomFlip("horizontal_and_vertical"),
tf.keras.layers.experimental.preprocessing.RandomRotation(0.2),
])
# TODO: Build and train your network.
model = tf.keras.Sequential([
data_augmentation,
feature_extractor,
tf.keras.layers.Dense(1028, activation="relu"),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(512, activation="relu"),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(512, activation="relu"),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(num_labels, activation = 'softmax')
])
# compile and fit the model on trainings_batches. Callback: Early Stopping to prevent overfitting.
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)
EPOCHS = 30
history = model.fit(training_batches,
epochs=EPOCHS,
validation_data=validation_batches,
callbacks=[early_stopping])
Epoch 1/30 16/16 [==============================] - 47s 3s/step - loss: 4.6349 - accuracy: 0.0245 - val_loss: 4.2259 - val_accuracy: 0.1814 Epoch 2/30 16/16 [==============================] - 45s 3s/step - loss: 3.8401 - accuracy: 0.1529 - val_loss: 2.8935 - val_accuracy: 0.3627 Epoch 3/30 16/16 [==============================] - 46s 3s/step - loss: 2.7643 - accuracy: 0.3108 - val_loss: 2.1083 - val_accuracy: 0.5098 Epoch 4/30 16/16 [==============================] - 44s 3s/step - loss: 1.9697 - accuracy: 0.4833 - val_loss: 1.6670 - val_accuracy: 0.5588 Epoch 5/30 16/16 [==============================] - 44s 3s/step - loss: 1.4584 - accuracy: 0.5833 - val_loss: 1.3662 - val_accuracy: 0.6363 Epoch 6/30 16/16 [==============================] - 44s 3s/step - loss: 1.1704 - accuracy: 0.6745 - val_loss: 1.2334 - val_accuracy: 0.6892 Epoch 7/30 16/16 [==============================] - 44s 3s/step - loss: 0.9072 - accuracy: 0.7275 - val_loss: 1.1077 - val_accuracy: 0.6873 Epoch 8/30 16/16 [==============================] - 46s 3s/step - loss: 0.7402 - accuracy: 0.7833 - val_loss: 1.0801 - val_accuracy: 0.6941 Epoch 9/30 16/16 [==============================] - 45s 3s/step - loss: 0.7023 - accuracy: 0.7961 - val_loss: 1.0898 - val_accuracy: 0.7010 Epoch 10/30 16/16 [==============================] - 45s 3s/step - loss: 0.6099 - accuracy: 0.8118 - val_loss: 0.9943 - val_accuracy: 0.7284 Epoch 11/30 16/16 [==============================] - 44s 3s/step - loss: 0.5664 - accuracy: 0.8343 - val_loss: 0.9773 - val_accuracy: 0.7284 Epoch 12/30 16/16 [==============================] - 45s 3s/step - loss: 0.4459 - accuracy: 0.8578 - val_loss: 0.9471 - val_accuracy: 0.7461 Epoch 13/30 16/16 [==============================] - 45s 3s/step - loss: 0.4044 - accuracy: 0.8745 - val_loss: 1.0270 - val_accuracy: 0.7314 Epoch 14/30 16/16 [==============================] - 44s 3s/step - loss: 0.4123 - accuracy: 0.8814 - val_loss: 0.9530 - val_accuracy: 0.7490 Epoch 15/30 16/16 [==============================] - 45s 3s/step - loss: 0.3420 - accuracy: 0.8971 - val_loss: 0.9188 - val_accuracy: 0.7539 Epoch 16/30 16/16 [==============================] - 45s 3s/step - loss: 0.2407 - accuracy: 0.9294 - val_loss: 0.9752 - val_accuracy: 0.7510 Epoch 17/30 16/16 [==============================] - 45s 3s/step - loss: 0.2052 - accuracy: 0.9402 - val_loss: 0.9604 - val_accuracy: 0.7588 Epoch 18/30 16/16 [==============================] - 45s 3s/step - loss: 0.2420 - accuracy: 0.9235 - val_loss: 0.9658 - val_accuracy: 0.7520 Epoch 19/30 16/16 [==============================] - 45s 3s/step - loss: 0.2298 - accuracy: 0.9216 - val_loss: 0.9834 - val_accuracy: 0.7559 Epoch 20/30 16/16 [==============================] - 45s 3s/step - loss: 0.1973 - accuracy: 0.9412 - val_loss: 0.9998 - val_accuracy: 0.7510
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']
training_loss = history.history['loss']
validation_loss = history.history['val_loss']
epochs_range=range(len(training_accuracy))
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
# Example: Testing the model and display the matches visually
for image_batch, label_batch in testing_batches.take(1):
ps = model.predict(image_batch)
images = image_batch.numpy().squeeze()
labels = label_batch.numpy()
plt.figure(figsize=(10,15))
for n in range(30):
plt.subplot(6,5,n+1)
plt.imshow(images[n], cmap = plt.cm.binary)
color = 'green' if np.argmax(ps[n]) == labels[n] else 'red'
plt.title(class_names[str(np.argmax(ps[n])+1)], color=color)
plt.axis('off')
loss, accuracy = model.evaluate(testing_batches)
97/97 [==============================] - 125s 1s/step - loss: 1.1842 - accuracy: 0.7200
# Printing the loss and accuracy on the test set
print('\nLoss on the TEST Set: {:,.3f}'.format(loss))
print('Accuracy on the TEST Set: {:.3%}'.format(accuracy))
Loss on the TEST Set: 1.184 Accuracy on the TEST Set: 71.995%
Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).
# TODO: Save your trained model as a Keras model.
t = time.time()
filepath = "./{}.h5".format(int(t))
model.save(filepath)
Load the Keras model you saved above.
URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
image_size= 224
feature_extractor = hub.KerasLayer(URL, input_shape=(image_size, image_size,3))
feature_extractor.trainable = False
filepath = "./1634573400.h5"
data_augmentation = tf.keras.Sequential([
tf.keras.layers.experimental.preprocessing.RandomFlip("horizontal_and_vertical"),
tf.keras.layers.experimental.preprocessing.RandomRotation(0.2),
])
# TODO: Load the Keras model
reloaded_model = tf.keras.models.load_model(filepath, custom_objects={'KerasLayer': hub.KerasLayer})
Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.
The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).
First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.
Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.
Finally, convert your image back to a NumPy array using the .numpy() method.
# TODO: Create the process_image function
def process_image(image_numpy, image_size=224):
image = tf.image.resize(image_numpy, (image_size, image_size))
image /= 255
return image.numpy()
To check your process_image function we have provided 4 images in the ./test_images/ folder:
The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.
from PIL import Image
image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)
processed_test_image = process_image(test_image)
fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()
# check the shape of the processed image
processed_test_image.shape
(224, 224, 3)
Once you can get images in the correct format, it's time to write the predict function for making inference with your model.
Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.
# TODO: Create the predict function
def predict(image_path, model, top_k=5):
image = Image.open(image_path)
image = np.asarray(image)
image = process_image(image)
image = np.expand_dims(image, axis=0)
prediction = model.predict(image)
prediction = prediction.reshape(102)
labels = np.argsort(prediction)[-top_k:][::-1]
probs = prediction[labels]
classes = [str(label+1) for label in labels]
return probs, classes
It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:
In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.
import matplotlib.pyplot as plt
import numpy as np
top_k = 5
# TODO: Plot the input image along with the top 5 classes
def plot_Images_and_Probability(image_path, top_k):
probs, classes = predict(image_path, reloaded_model, top_k)
im = Image.open(image_path)
test_image = np.asarray(im)
processed_test_image = process_image(test_image)
names = list()
for x_class in classes:
names.append(class_names[x_class])
plt.rcdefaults()
fig, (ax1, ax2) = plt.subplots(1,2)
ax1.imshow(processed_test_image)
ax1.axis("off")
ax2.barh(names, probs*100)
ax2.set_title('Class Probability')
ax2.set_xlabel("Probability in Percent")
ax2.set_xlim([0,100])
plt.tight_layout()
plt.show()
image_path = "./test_images/cautleya_spicata.jpg"
plot_Images_and_Probability(image_path, top_k)
image_path = "./test_images/hard-leaved_pocket_orchid.jpg"
plot_Images_and_Probability(image_path, top_k)
image_path = "./test_images/orange_dahlia.jpg"
plot_Images_and_Probability(image_path, top_k)
image_path = "./test_images/wild_pansy.jpg"
plot_Images_and_Probability(image_path, top_k)